﻿namespace jQube.Web.UI.Controls
{
    using System.ComponentModel;
    using System.Text;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using System.Drawing;
    using System;

    [RequiredScript("jQube.Resources.Controls.ModalPopup.jquery.modalPopup-1.0.0.js")]
    [RequiredStyleSheet("jQube.Resources.Controls.ModalPopup.ModalPopup.css")]
    [ToolboxBitmap(typeof(ModalPopup), "jQube.Resources.Controls.ModalPopup.ModalPopup.ico")]
    public class ModalPopup : WebControl, IPostBackEventHandler, IScriptHandledControl
    {

        public ModalPopup()
            : base(HtmlTextWriterTag.Div)
        {
            this.BackgroundCssClass = "jqube-modalpopup-background";
            this.PopupBorderCssClass = "jqube-modalpopup-popup_border";
            this.RepositionMode = RepositionMode.ResizeScroll;
            this.CloseOnBackgroundClick = false;
            this.CloseOnEscapeKey = false;
            this.Title = string.Empty;
            this.EnableOkButton = true;
            this.OkButtonText = "OK";
            this.EnableCancelButton = true;
            this.CancelButtonText = "Cancel";
        }

        public event EventHandler ModalOk;

        [Category("Appearance")]
        [DefaultValue("")]
        public string Title { get; set; }

        [Category("Design")]
        [DefaultValue("jqube-modalpopup-background")]
        public string BackgroundCssClass { get; set; }

        [Category("Design")]
        [DefaultValue("jqube-modalpopup-popup_border")]
        public string PopupBorderCssClass { get; set; }

        [Category("Behavior")]
        [IDReferenceProperty(typeof(WebControl))]
        public string TriggerControlID { get; set; }

        [Category("Behavior")]
        [DefaultValue(RepositionMode.ResizeScroll)]
        public RepositionMode RepositionMode { get; set; }

        [Category("Behavior")]
        [DefaultValue(false)]
        public bool CloseOnBackgroundClick { get; set; }

        [Category("Behavior")]
        [DefaultValue(false)]
        public bool CloseOnEscapeKey { get; set; }

        [Category("Behavior")]
        [DefaultValue(true)]
        public bool EnableOkButton { get; set; }

        [Category("Behavior")]
        [DefaultValue(true)]
        public bool EnableCancelButton { get; set; }

        [Category("Appearance")]
        [DefaultValue("OK")]
        public string OkButtonText { get; set; }

        [Category("Appearance")]
        [DefaultValue("Cancel")]
        public string CancelButtonText { get; set; }

        [Category("Behavior")]
        [DefaultValue("")]
        public string OnOkClientScript { get; set; }

        [Category("Behavior")]
        [DefaultValue("")]
        public string OnCancelClientScript { get; set; }

        [Browsable(false)]
        [EditorBrowsable(EditorBrowsableState.Never)]
        [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
        public ModalPopupContenPanel ContentContainer { get; set; }

        [Browsable(false)]
        [DefaultValue(null)]
        [PersistenceMode(PersistenceMode.InnerProperty)]
        [TemplateContainer(typeof(ModalPopupContenPanel))]
        [TemplateInstance(TemplateInstance.Single)]
        public virtual ITemplate Content { get; set; }

        protected override void OnInit(System.EventArgs e)
        {
            ScriptManager scriptManager = ScriptManager.GetCurrent(base.Page);

            scriptManager.AddRequiredScript(typeof(ModalPopup));
            scriptManager.AddRequiredStyleSheet(typeof(ModalPopup));

            scriptManager.AddInitilizationScript(
                    string.Format("$(\"#{0}\").modalPopup({1});",
                        this.ClientID,
                        this.GetInitilizationOptions()));

            base.OnInit(e);
        }

        public string GetInitilizationOptions()
        {
            StringBuilder options = new StringBuilder();

            options.AppendFormat(
@"
            backgroundClass : ""{0}"",
            popupBorderCssClass : ""{1}"",
            triggerControlID : ""{2}"",
            repositionMode : {3},
            closeOnBackgroundClick : {4},
            closeOnEscapeKey : {5},
            title: ""{6}"",
            enabledOkButton: {7},
            okButtonText: ""{8}"",
            enabledCancelButton: {9},
            cancelButtonText: ""{10}""
",
              this.BackgroundCssClass,
              this.PopupBorderCssClass,
              this.GetTriggerClientID(),
              (int)this.RepositionMode,
              this.CloseOnBackgroundClick.ToString().ToLower(),
              this.CloseOnEscapeKey.ToString().ToLower(),
              this.Title,
              this.EnableOkButton.ToString().ToLower(),
              this.OkButtonText,
              this.EnableCancelButton.ToString().ToLower(),
              this.CancelButtonText);

            if (!string.IsNullOrWhiteSpace(this.OnOkClientScript))
            {
                options.AppendFormat(
@",
            onOk: function () #x7B {0} #x7D", this.OnOkClientScript);
            }

            if (!string.IsNullOrWhiteSpace(this.OnCancelClientScript))
            {
                options.AppendFormat(
@",
            onCancel: function () #x7B {12} #x7D", this.OnCancelClientScript);
            }

            options.Insert(0, " { ");
            options.Append("\t}");
            options.Replace("#x7B", "{");
            options.Replace("#x7D", "}");

            return options.ToString();
        }

        private string GetTriggerClientID()
        {
            try
            {
                return base.Page.FindControl(this.TriggerControlID).ClientID;
            }
            catch
            {
                throw new ArgumentException(
                    string.Format("The control {0} can not be found", this.TriggerControlID),
                    "TriggerControlID");
            }
        }

        protected override void CreateChildControls()
        {
            this.ContentContainer = new ModalPopupContenPanel(this);
            this.Controls.Add(this.ContentContainer);

            if (this.Content != null)
                this.Content.InstantiateIn(this.ContentContainer);

            base.CreateChildControls();
        }

        public void RaisePostBackEvent(string eventArgument)
        {
            if (this.ModalOk != null)
                this.ModalOk.Invoke(this, EventArgs.Empty);
        }
    }
}
